#!/usr/bin/env python
import pyPdf
from Pamplemousse.preprocess.normalize import normalize


class Pamplemousse(object):
    def __init__(self, inputfile, passwd='', enc='utf-8', normalgo='NFKD'):
        print 'WARNING:  No guarantee of text order.  Do not use for order-sensitive classifiers'
        self.pdf_doc = inputfile
        self.passwd = passwd
        self.enc = enc
        self.output_enc = enc
        self.normalize_algo = normalgo

        self.raw = None
        self.pages = None
        self._parse_pages()

    def __del__(self):
        # Delete PDF file
        print "Debug Comment:  PDF has not been deleted"
        # os.remove(self.pdf_doc)  # NOTE:  uncomment in production code

    def _parse_pages(self):
        pdf = pyPdf.PdfFileReader(file(self.pdf_doc, "rb"))

        self.pages = [normalize(pdf.getPage(i).extractText() + '\n', self.normalize_algo) for i in range(0, pdf.getNumPages())]
        self.raw = pdf

        for i, page in enumerate(self.pages):
            self.pages[i] = " ".join(page.replace(u"\xa0", " ").strip().split())

        return self.pages  # each page is a long unicode string


def get_text(path):
    '''No guarantee of text order.  Don't use for order-sensitive classifiers'''
    # Load PDF into pyPDF
    pdf = pyPdf.PdfFileReader(file(path, "rb"))
    # Iterate pages
    content = ""
    for i in range(0, pdf.getNumPages()):
        content += pdf.getPage(i).extractText() + "\n"  # Extract text from page and add to content
    # Collapse whitespace
    content = " ".join(content.replace(u"\xa0", " ").strip().split())
    return content
